<template>
    <div>
        <div ref="experimentContainer"></div>

    </div>
</template>
<script setup>
import mp0 from '../assets/0.mp3'
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios'
const router = useRouter();
const scores = ref(0);
const lastscore = ref(0);
const life = ref(3);
const timeline = ref([]);

let level = 21;
let responnumber = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '0', "回退", "确认"]
let size = [3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]
let range = [4, 6, 9, 4, 6, 9, 4, 6, 9, 4, 6, 9, 4, 6, 9, 4, 6, 9, 4, 6, 9]
const nowstep = ref(0);
const inputvalue = ref("请输入");
const correctNumbers = ref();
import { useAuthStore } from '../store/index';
const Store = useAuthStore();
let id = Store.user.stuId;
onMounted(async () => {
    Store.setuptrue();
    axios({
        method: "get",
        url: `/interface/res/max-score-voice-number`,
        params: {
            stuId: id,
            type: "pos"
        }
    }).then(async (res) => {
        if (res.data.data != null) {

            lastscore.value = res.data.data.score
        }
        console.log(lastscore.value);
        await init();
        jsPsych.init({
            timeline: timeline.value,

        });
    })
    // var start = {
    //     type: 'html-button-response',
    //     stimulus: `
    //     <h1>最高分：${lastscore.value}</h1>
    //     <p class="jsp">指导语;欢迎来挑战视觉数字闯关</p>
    //     <p class="jsp">记住屏幕上挨个出现的数字，一会在答案按出现顺序输入。</p>
    //     <p class="jsp">游戏里，你一共有三点生命，关卡挑战失败就会扣减一点</p>
    //     <p class="jsp">加油获得最高分吧!</p>`,
    //     choices: ['开始游戏'],
    //     prompt: ``
    // };
    // var new_timeline = {
    //     timeline: [start]
    // }

    // jsPsych.addNodeToEndOfTimeline(new_timeline)

    // addrespon()
    // addrespon()
})
const init = () => {

    return new Promise((resolve) => {
        var enter_fullscreen = {
            type: 'fullscreen',
            message: "<h1>进入全屏</h1><br/>",
            button_label: "继续",
            fullscreen_mode: true
        }
        timeline.value.push(enter_fullscreen);
        var start = {
            type: 'html-button-response',
            stimulus: `
        <h1>最高分：${lastscore.value}</h1>

        <p class="jsp">请将听到的数字按顺序输入</p>
   `,
            choices: ['开始游戏'],
            prompt: ``
        };
        var preload = {
            type: 'preload',
            auto_preload: true
        }
        timeline.value.push(preload);
        timeline.value.push(start);
        var levelitem = {
            timeline: dealitem(0, 4, 3)
        }
        timeline.value.push(levelitem);
        resolve();
    })
}
const dealitem = (item1, item2, item3) => {
    correctNumbers.value = generateUniqueRandomNumbers(item1, item2, item3)
    let result = [];
    var start = {
        type: 'html-button-response',
        stimulus: `<h1>第${Math.floor(nowstep.value / 2) + 1}关第${nowstep.value % 2 + 1}小关</h1>`,
        choices: ["<h1>继续</h1>"],
        // trial_duration: 1000,
        prompt: ``,

    };
    result.push(start);
    var fixation = {
        type: 'html-keyboard-response',
        stimulus: '<div style="font-size:40px;">+</div>',
        choices: jsPsych.NO_KEYS,
        trial_duration: 500
    }
    result.push(fixation);
    for (let i = 0; i < item3; i++) {
        var item = {
            type: 'audio-keyboard-response',
            prompt: `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img"></div>
                <img style="width:80%; height:80%" src="${new URL(`../assets/laba.gif`, import.meta.url).href}" alt="">`,
            choices: jsPsych.NO_KEYS,
            trial_ends_after_audio: true,
            stimulus: `${new URL(`../assets/${correctNumbers.value[i]}.mp3`, import.meta.url).href}`,
            // trial_duration: 1000,
            on_start: function () {
                console.log(i);
                if (life.value == 3) {
                    this.prompt = `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img"></div>
                <img style="width:80%; height:80%" src="${new URL(`../assets/laba.gif`, import.meta.url).href}" alt="">`
                } else if (life.value == 2) {
                    this.prompt = `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div>
                <img style="width:80%; height:80%" src="${new URL(`../assets/laba.gif`, import.meta.url).href}" alt="">`
                } else if (life.value == 1) {
                    this.prompt = `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div>
                <img style="width:80%; height:80%" src="${new URL(`../assets/laba.gif`, import.meta.url).href}" alt="">`
                }
            }
        };
        result.push(item);
    };
    var resopen = {
        type: 'html-button-response',
        stimulus: `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img"></div><h1>${inputvalue.value}</h1>`,
        choices: responnumber,
        // trial_duration:1000,
        prompt: ``,
        on_start: function (data) {
            if (inputvalue.value.length == 0) {
                inputvalue.value = "请输入"
            }
            if (life.value == 3) {
                this.stimulus = `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img"></div><h1>${inputvalue.value}</h1>`
            } else if (life.value == 2) {
                this.stimulus = `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div><h1>${inputvalue.value}</h1>`
            } else if (life.value == 1) {
                this.stimulus = `<h1 class="score">当前得分：${scores.value}</h1><div id="imgbox"><img src="${new URL(`../assets/285639_heart_icon.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img">
                <img src="${new URL(`../assets/掉血后图片.png`, import.meta.url).href}" alt="" class="img"></div><h1>${inputvalue.value}</h1>`
            }
            if (inputvalue.value != "请输入") {
                this.choices = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '0', "回退", "确认"]
            } else {
                this.choices = ['7', '8', '9', '4', '5', '6', '1', '2', '3', '0', "回退"]
            }

        },
        on_finish: async function (data) {
            console.log(data);
            if (responnumber[data.response] != "回退" && responnumber[data.response] != "确认") {
                if (inputvalue.value == "请输入") {
                    inputvalue.value = ""
                }
                inputvalue.value += responnumber[data.response]
            } else if (responnumber[data.response] == "回退"&&inputvalue.value!="请输入") {
                console.log(jsPsych);
                // var new_timeline = {
                //     timeline: [resopen, resopen]
                // }
                // jsPsych.addNodeToEndOfTimeline(new_timeline, () => { })

                console.log(inputvalue.value);
                inputvalue.value = inputvalue.value.slice(0, -1);
            }
            if ( responnumber[data.response] == "确认") {
                console.log("nowstep" + nowstep.value);
                if (correctNumbers.value.join("") == inputvalue.value) {
                    scores.value++;
                    nowstep.value++;
                    if (nowstep.value == 42) {
                        success()
                    } else {
                        if (nowstep.value % 2 == 0) {
                            gotostep()
                        }
                    }
                } else {

                    life.value--;
                    if (life.value == 0) {
                        dead();

                    } else {
                        back()
                    }
                    nowstep.value--;
                    if (nowstep.value < 0) {
                        nowstep.value = 0;
                    }

                }

                if (life.value != 0) {


                    var levelitem = {
                        timeline: dealitem(0, range[Math.floor(nowstep.value / 2)], size[Math.floor(nowstep.value / 2)])
                    }
                    console.log(levelitem);
                    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
                }
                console.log(nowstep.value);


                inputvalue.value = "";
                const timestamp = Date.now(); // 获取当前时间戳
                const date = new Date(timestamp); // 使用时间戳创建一个 Date 对象

                // 获取时、分、秒
                const hours = date.getHours().toString().padStart(2, '0'); // 获取小时，并确保始终是两位数
                const minutes = date.getMinutes().toString().padStart(2, '0'); // 获取分钟，并确保始终是两位数
                const seconds = date.getSeconds().toString().padStart(2, '0'); // 获取秒，并确保始终是两位数

                // 构建时间字符串
                const timeString = `${hours}:${minutes}:${seconds}`;
                await axios({
                    method: "post",
                    url: `/interface/res/voice-number-pos`,
                    data: {
                        "level": Math.floor(nowstep.value / 2),
                        "num": size[Math.floor(nowstep.value / 2)],
                        "score": scores.value,
                        "time": timeString,
                        "stuId": id
                    }
                }).then(async (res) => {
                    console.log(res);
                })
            } else {
                var new_timeline = {
                    timeline: [resopen]
                }
                jsPsych.addNodeToEndOfTimeline(new_timeline, () => { })
            }

        }
    };
    result.push(resopen);


    return result;
}
function gotostep() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>很棒，恭喜过关！</h1>
        <img src="${new URL(`../assets/gotostep.png`, import.meta.url).href}" alt="">
        <h1>已闯过${Math.floor(nowstep.value / 2)}关</h1>
       `,
        choices: [`进入第${Math.floor(nowstep.value / 2) + 1}关`],
        prompt: ``
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function dead() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>你的挑战机会用完了，下次再挑战吧!</h1>
        <h1>得分${scores.value}</h1>
        <img src="${new URL(`../assets/dead.png`, import.meta.url).href}" alt="" >
        <h1>已闯过${Math.floor(nowstep.value / 2)}关</h1>`,
        choices: ['退出游戏'],
        prompt: ``,
        on_finish: function () {
            router.push('/select')
        }
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function back() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>没有过关，请继续努力!</h1>
        <img src="${new URL(`../assets/back.png`, import.meta.url).href}" alt="" >
        <h1>第${Math.floor(nowstep.value / 2) + 1}关</h1>`,
        choices: ['重新闯关'],
        prompt: ``
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function success() {
    var start = {
        type: 'html-button-response',
        stimulus: `
        <h1>恭喜你全部闯关成功</h1>
        <img src="${new URL(`../assets/success.png`, import.meta.url).href}" alt="" >
        <h1>第${Math.floor(nowstep.value / 2) + 1}关</h1>`,
        choices: ['返回'],
        prompt: ``,
        on_finish: function () {
            router.push('/select')
        }
    };
    var levelitem = {
        timeline: [start]
    }
    console.log(levelitem);
    jsPsych.addNodeToEndOfTimeline(levelitem, () => { })
}
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}
function generateUniqueRandomNumbers(min, max, count) {
    const result = [];
    for (let i = 0; i < count; i++) {
        let x=Math.floor(Math.random() * (max - min + 1)) + min
        if (i === 0) {
            result.push(x);
        } else {
            if (x==result[i-1]){
                i--
            }else{
                result.push(x);
            }
        }
    }
    return result;
}

</script>
<style>
.jsp {
    font-size: 2rem;
}

.jspsych-btn {
    font-size: 1.5rem;
}

#jspsych-html-button-response-btngroup {
    display: grid;
    justify-content: center;
    grid-template-columns: repeat(3, 50px);
    grid-auto-rows: 50px;
    gap: 5px;
}

button {
    padding: 10px;
    font-size: 16px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f0f0f0;
    cursor: pointer;
}

button:hover {
    background-color: #e0e0e0;
}


#imgbox {
    height: 20px;
    width: 300px;
    position: fixed;
    right: 0px;
    top: 0px;
}

#imgbox img {
    width: 30%;
}

.score {
    position: fixed;
    left: 0px;
    top: 0px;
}
</style>